import { login } from "@apis/user"
import {
  getItem,
  setItem,
  TokenKey /* , removeToken, removeItem */
} from "@utils/auth"
// import { resetRouter } from '@/router';
const state = {
  token: getItem(TokenKey)
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  }
}
const loginCallback = (response, commit, resolve) => {
  const {
    data: { token = "" }
  } = response
  commit("SET_TOKEN", token)
  setItem(TokenKey, token)
  resolve()
}
const actions = {
  // user logins
  login({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      login(userInfo)
        .then((response) => {
          loginCallback(response, commit, resolve)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },
  setToken({ commit }, token) {
    commit("SET_TOKEN", token)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
